<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/3/19
 * Time: 10:35
 */

namespace app\index\controller;


use think\facade\Cache;
use think\facade\Request;

class Login
{
    protected $jscodeUrl = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';

    /**
     * 通过小程序登录获取访问令牌
     * @param $jscode
     * @return string
     */
    public function getTokenByJsCode($jscode)
    {
        $requestUrl = sprintf($this->jscodeUrl,config('wechat.applet_appid'),config('wechat.applet_secret'),$jscode);
        $result = https_request($requestUrl);
        $data = json_decode($result,true);
        if ( isset($data['errcode']) ) {
            // 记录日志  抛异常
            $this->error("请求有问题"  . $data['errmsg']);
        }

        $openid = $data['openid'];
        $token = Request::token();
//        $token = md5( date('YmdHis') );
//        Cache::set($token,$openid);
        Cache::set("token",$token);
        return json(['openid' => $openid, 'token' => $token]);
    }
}